package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 雪花算法 ID 生成器
 */
@Component
public class SnowflakeIdGenerator {

    // 每部分占用的位数
    private final long nodeIdBits = 10L;
    private final long sequenceBits = 12L;

    // 最大值
    private final long maxSequence = ~(-1L << sequenceBits);

    private final long nodeIdShift = sequenceBits;
    private final long timestampLeftShift = sequenceBits + nodeIdBits;

    private long lastTimestamp = -1L;
    private long sequence = 0L;
    private final long workerId;

    /**
     * 创建 SnowflakeIdGenerator 实例
     *
     * @param workerId 工作节点 ID，范围 0~1023
     */
    @Autowired
    public SnowflakeIdGenerator(@Value("${snowflake.worker-id}") long workerId) {
        this.workerId = workerId;
    }

    /**
     * 生成下一个 ID
     *
     * @return 下一个 json long ID
     */
    public synchronized long nextId56() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & maxSequence;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }

        lastTimestamp = timestamp;

        return (timestamp << (timestampLeftShift-12))
                | (workerId << nodeIdShift)
                | sequence;

    }
    /**
     * 生成下一个 ID
     *
     * @return 下一个 ID
     */
        public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & maxSequence;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }

        lastTimestamp = timestamp;

        return (timestamp << timestampLeftShift)
               | (workerId << nodeIdShift)
               | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
}
